package ua.kharkov.knure.pereverziev.diploma.web.command.ajax;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.ServiceFactory;
import ua.kharkov.knure.pereverziev.diploma.db.entity.User;
import ua.kharkov.knure.pereverziev.diploma.util.email.EmailSender;
import ua.kharkov.knure.pereverziev.diploma.web.command.Command;

public class PasswordRecovery implements Command {

	private static final Logger log = Logger.getLogger(PasswordRecovery.class);

	@Override
	public String execute(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {

		final String email = request.getParameter("email");
		log.info("Request parameter: email --> " + email);

		final User user = ServiceFactory.getInstance().getUserService()
				.getByEmail(email);
		if (user == null)
			return "No user found";
		try {
			EmailSender.send(email, "Password recovery", "Your password: \""
					+ user.getPassword() + "\"");
		} catch (final Exception e) {
			e.printStackTrace();
			log.error("Error while recovering password");
			return "Error pccured while sending e-mail to adress " + email;
		}
		return "Letter was sent to adress " + email;
	}

}
